﻿using Ldt.DataEngine.RuleAssemble;
using LdtDataEngin.ModuleDetail.PersonnelAnalysis.PersonnelBase;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.DateAssemble;
using LdtJudge.DataEngine.Common.StringAssemble;
using LdtJudge.DataEngine.Model.Personnel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace LdtDataEngin.ModuleDetail.PersonnelAnalysis
{
    /// <summary>
    /// 人员转换
    /// </summary>
    public class PersonnelConversion
    {
        /// <summary>
        /// 人员信息集合
        /// </summary>
        public IList<ElementSpokeName> spokenamelist { get; set; }


        /// <summary>
        /// 根据将文本中代称信息转换为人员信息
        /// </summary>
        /// <param name="ListName"></param>
        /// <param name="originalText"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public string ReplaceShortNameToFullName(IList<ElementSpokeName> ListName, string originalText, string flag = "")
        {
            originalText = originalText.Replace("原告方", "**1");
            originalText = originalText.Replace("被告方", "**2");
            originalText = originalText.Replace("犯罪嫌疑人", "被告人");
            spokenamelist = ListName;
            originalText = dealPre(originalText);
            string newOriginalText = FormatOriginalText(originalText, ListName);
            try
            {
                //做被一到被九的替换

                var accusedPeople = ListName.Where(a => a.ES_SuitDrgreeID == "90").ToList();
                string name = string.Empty;
                string _roleCHNNum = string.Empty;
                string _roleintNum = string.Empty;
                string replacecontent = string.Empty;
                ChnNumFormat cnf = new ChnNumFormat();
                foreach (var s in accusedPeople)
                {
                    name += s.ES_FullName + "|";
                    if ((Convert.ToInt32(s.ES_RoleIndex) < 10))
                    {
                        _roleCHNNum += cnf.NumToChn(s.ES_RoleIndex.ToString());
                        _roleintNum += s.ES_RoleIndex;
                    }
                    else
                    {
                        _roleCHNNum = "一二三四五六七八九十";
                        _roleintNum = "\\d";
                    }
                }
                replacecontent = _roleCHNNum + "、,，" + _roleintNum;
                string beiReg = RuleParseClass.GetRegString("CourtSpokeParseA10");
                if (!string.IsNullOrEmpty(name))
                {
                    beiReg = beiReg.Replace("(@{Name})", name.Remove(name.Length - 1, 1));
                    beiReg = beiReg.Replace("(@{Name1})", replacecontent);
                }
                Regex bei = new Regex(beiReg);
                string rpReg = RuleParseClass.GetRegString("CourtSpokeParseA4");
                Regex rp = new Regex(rpReg);
                string chineseNumber = "一二三四五六七八九123456789";
                var accused = ListName.Where(a => a.ES_SuitDrgreeID == "90").OrderBy(a => a.ES_RoleIndex).ToList();
                Match m = bei.Match(newOriginalText);
                #region 进行提取
                while (m != null && m.Value != string.Empty && accused.Count > 0)//&& accused.Count>0 ljx 2017-07-21添加条件判断！ 防止死循环
                {
                    string r = rp.Replace(m.Value, "");
                    //只出现一次 比如 被一 被告一的替换
                    if (r.ToArray().Count() == 1)
                    {
                        char cnum = m.Value.ToArray().Last().ToString().ToCharArray().First();
                        int num = chineseNumber.ToArray().ToList().FindIndex(a => a == cnum);
                        if ((num % 9 + 1.0) <= accused.Count)
                        {
                            string s = newOriginalText.Substring(m.Index, m.Value.Length);
                            newOriginalText = newOriginalText.Remove(m.Index, m.Length); //删除匹配到的内容
                            if (string.IsNullOrEmpty(flag))
                            {
                                var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                if (accuse != null)
                                {
                                    newOriginalText = newOriginalText.Insert(m.Index, "被告" + accuse.ES_FullName);
                                }
                            }
                            else
                            {
                                var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                if (accuse != null)
                                {
                                    newOriginalText = newOriginalText.Insert(m.Index, accuse.ES_FullName);
                                }
                            }
                        }
                        else
                        {
                            if (accused.Count > 9)
                            {
                                string s = newOriginalText.Substring(m.Index, m.Value.Length);
                                newOriginalText = newOriginalText.Remove(m.Index, m.Length); //删除匹配到的内容
                                if (string.IsNullOrEmpty(flag))
                                {
                                    var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                    if (accuse != null)
                                    {
                                        newOriginalText = newOriginalText.Insert(m.Index, "被告" + accuse.ES_FullName);
                                    }
                                }
                                else
                                {
                                    var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                    if (accuse != null)
                                    {
                                        newOriginalText = newOriginalText.Insert(m.Index, accuse.ES_FullName);
                                    }
                                }
                            }
                        }
                    }
                    //出现多次 如 被一、二、三的替换
                    else
                    {
                        string replaceText = "";
                        string[] result = r.Split(new char[] { '、', ',', ',' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var it in result)
                        {
                            try
                            {
                                int num = (int)int.Parse(LdFormat.DecodeNumberCn(it.ToString()).ToString());
                                num -= 1;
                                if (num <= accused.Count)
                                {
                                    if (string.IsNullOrEmpty(flag))
                                    {
                                        replaceText = replaceText + "被告" + accused[num].ES_FullName + "、";

                                    }
                                    else
                                    {
                                        replaceText = replaceText + accused[num].ES_FullName + "、";

                                    }
                                }
                            }
                            catch (Exception err)
                            {
                                replaceText = replaceText + it;

                            }
                        }
                        newOriginalText = newOriginalText.Remove(m.Index, m.Length);
                        //判断传进来的是被告三、还是被告三、四
                        if (result.Length == 1)
                        {
                            newOriginalText = newOriginalText.Insert(m.Index, replaceText);
                        }
                        else
                        {
                            newOriginalText = newOriginalText.Insert(m.Index, replaceText.Remove(replaceText.Length - 1, 1));
                        }
                    }

                    m = bei.Match(newOriginalText);
                }
                #endregion
            }
            catch (Exception err)
            {

            }
            string regPattern = string.Empty;
            var query = from item in ListName
                        where !string.IsNullOrWhiteSpace(item.ES_SuitDegreeName) && (!string.IsNullOrWhiteSpace(item.ES_FullName) || !string.IsNullOrWhiteSpace(item.ES_ShortName))
                        group item by item.ES_SuitDegreeName into g
                        select new { Group = g.Key, Member = g };
            string Renyuan = RuleParseClass.GetRegString("ExtractEsSpokeName");
            foreach (var item in query)
            {
                string allFullName = string.Join("|", item.Member.Select(x => x.ES_FullName).ToList<string>());
                string allShortName = string.Join("|", item.Member.Select(x => x.ES_FullName).ToList<string>());
                allFullName += (allShortName == string.Empty) ? "" : "|" + allShortName;
                regPattern += (regPattern == "") ? "" : "|";
                regPattern += Renyuan.Replace("@{Name}", item.Group).Replace("@{Name_a}", allFullName.Replace("*", "\\*"));
            }
            //替换值文本集合0
            Dictionary<string, string> replaceDict = new Dictionary<string, string>();

            MatchCollection matchArr = Regex.Matches(newOriginalText, regPattern);
            if (!string.IsNullOrEmpty(regPattern))
            {
                List<Tuple<int, int, int>> replacedList = new List<Tuple<int, int, int>>();//记录已替换的位置
                for (int z = matchArr.Count - 1; z >= 0; z--)
                {
                    Match match = matchArr[z];
                    string extractValue = match.Value;
                    string extrname = extractValue.Replace("原告", "").Replace("、", "").Replace(",", "").Trim();
                    //string extrname = extractValue;

                    if (extractValue == "原告" || extractValue.IndexOf("原告") == -1 || extrname == null || LdFormat.DecodeNumberCn(extrname) == 1)
                    {
                        //处理匹配到 比如三被告共同的情况 此情况下被告不做替换 第一、二被告----第一被告、第二被告
                        try
                        {
                            if (newOriginalText.Length >= match.Index && match.Index - 2 > -1)
                            {
                                string last = newOriginalText.Substring(match.Index - 2, 2);//取名称前2个字

                                if (RuleParseClass.IsMatch("CourtSpokeParseA6", last))
                                {
                                    continue;
                                }
                            }
                        }
                        catch (Exception err)
                        {

                        }
                        string replaceValue = string.Empty;
                        List<string> queryperson = new List<string>();
                        if (replaceDict.ContainsKey(extractValue))
                        {
                            replaceValue = replaceDict[extractValue];
                        }
                        else
                        {

                            IList<ElementSpokeName> matchList2 = GetMatchSpokeManByRoleName(ListName, extractValue.Replace("、", ""));

                            if (string.IsNullOrEmpty(flag))
                            {
                                queryperson = (from person in matchList2
                                               where (person.ES_SuitDegreeName != "" || person.ES_FullName != "")
                                               select person.ES_SuitDegreeName + person.ES_FullName).Distinct().ToList();
                            }
                            else
                            {
                                queryperson = (from person in matchList2
                                               where (person.ES_SuitDegreeName != "" || person.ES_FullName != "")
                                               select person.ES_FullName).Distinct().ToList();
                            }
                            replaceValue = String.Join("、", queryperson);
                            var next = matchArr.Cast<Match>().SingleOrDefault(a => a.Index == match.Index + match.Length);
                            //兼容人员替换后无顿号的情况
                            if (extractValue.EndsWith("、") && next != null)
                            {
                                replaceDict.Add(extractValue, replaceValue + "、");
                            }
                            else if (extractValue.EndsWith("、") && next == null)
                            {
                                replaceDict.Add(extractValue, replaceValue);
                            }
                            else
                            {
                                replaceDict.Add(extractValue, replaceValue);
                            }
                        }
                        try
                        {
                            string test = newOriginalText.Substring(match.Index + match.Length);
                            bool isreplace = true;
                            foreach (var sp in ListName)
                            {
                                if (sp != null && sp.ES_ShortName != null)
                                {
                                    if ((replaceValue.IndexOf(sp.ES_ShortName) > 0 && test.StartsWith(sp.ES_ShortName)) || replaceValue == "")
                                    {
                                        isreplace = false;
                                        break;
                                    }
                                }
                            }
                            if (isreplace)
                            {
                                newOriginalText = newOriginalText.Remove(match.Index, match.Length);
                                newOriginalText = newOriginalText.Insert(match.Index, replaceValue);
                            }
                        }
                        catch (Exception err)
                        {
                        }
                        var it = replacedList.LastOrDefault();
                        //判断上次替换之前名称是否连接
                        if (it != null)
                        {
                            if (it.Item1 == match.Index + match.Length)
                            {
                                if (!string.IsNullOrEmpty(replaceValue))
                                {
                                    if (newOriginalText.ToArray()[match.Index + replaceValue.Length - 1] != '、')
                                    {
                                        newOriginalText = newOriginalText.Insert(match.Index + replaceValue.Length, "、");
                                    }
                                }

                            }
                        }
                        if (!replaceValue.EndsWith("、"))
                        {
                            //记录上次替换的位置 防止原被告这种直接连接的替换后无顿号
                            Tuple<int, int, int> tp = new Tuple<int, int, int>(match.Index, match.Length, replaceValue.Length);
                            replacedList.Add(tp);
                        }
                    }

                }
            }

            return newOriginalText.Replace("**1", "原告方").Replace("**2", "被告方").Replace("**3", "原、被告");
        }


        /// <summary>
        /// 优化后原文中替换人员代称---支持各种案件类型
        /// </summary>
        /// <param name="ListName"></param>
        /// <param name="originalText"></param>
        /// <param name="caseType"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public string ReplaceShortNameToOriginalText(IList<ElementSpokeName> ListName, string originalText, string caseType, string flag = "")
        {
            #region 用户原告方被告方特殊处理

            originalText = originalText.Replace("原告方", "**1");
            originalText = originalText.Replace("被告方", "**2");

            originalText = originalText.Replace("犯罪嫌疑人", "被告人");
            originalText = originalText.Replace("被告人", "被告");

            #endregion

            spokenamelist = ListName;
            //处理“原被告”的问题
            originalText = dealPre(originalText);
            string name = string.Empty;
            //格式化文本
            string newOriginalText = FormatOriginalText(originalText, ListName, caseType);
            //得到人员诉讼地位分组信息
            Dictionary<string, IGrouping<string, ElementSpokeName>> SuitIDList = spokenamelist.GroupBy(a => a.ES_SuitDrgreeID).ToDictionary(a => a.Key, b => b);

            if (caseType == "b1" || caseType == "jb1")
            {
                string suitid = "";
                if (caseType == "b1")
                {
                    suitid = "90";
                }
                else if (caseType == "jb1")
                {
                    suitid = "297";
                }
                try
                {
                    //做被一到被九的替换
                    var accusedPeople = ListName.Where(a => a.ES_SuitDrgreeID == suitid).ToList();

                    string _roleCHNNum = string.Empty;
                    string _roleintNum = string.Empty;
                    string replacecontent = string.Empty;
                    string suit = string.Empty;
                    ChnNumFormat cnf = new ChnNumFormat();

                    for (int i = 0; i < accusedPeople.Count; i++)
                    {
                        var people = accusedPeople[i];
                        if (i == accusedPeople.Count || string.IsNullOrEmpty(suit))
                        {
                            string suitname = people.ES_SuitDegreeName;
                            if (suitname == "犯罪嫌疑人")
                            {
                                suitname = "被告";
                            }
                            suit += suitname;
                        }
                        else if (!string.IsNullOrEmpty(suit))
                        {
                            string suitname = people.ES_SuitDegreeName;
                            if (suitname == "犯罪嫌疑人")
                            {
                                suitname = "被告";
                            }
                            suit += "|" + suitname;
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            name = people.ES_FullName;
                        }
                        else
                        {
                            name += "|" + people.ES_FullName;
                        }

                        if ((Convert.ToInt32(people.ES_RoleIndex) < 10))
                        {
                            _roleCHNNum += cnf.NumToChn(people.ES_RoleIndex.ToString());
                            _roleintNum += people.ES_RoleIndex;
                        }
                        else
                        {
                            _roleCHNNum = "一二三四五六七八九十";
                            _roleintNum = "\\d";
                        }

                    }
                    replacecontent = _roleCHNNum + "、,，" + _roleintNum;
                    string beiReg = RuleParseClass.GetRegString("CourtSpokeParseA10");
                    if (!string.IsNullOrEmpty(name))
                    {
                        beiReg = beiReg.Replace("(@{Name})", name.Remove(name.Length - 1, 1));
                        beiReg = beiReg.Replace("(@{Name1})", replacecontent);
                        beiReg = beiReg.Replace("@{suit}", suit);
                    }
                    Regex bei = new Regex(beiReg);
                    string rpReg = RuleParseClass.GetRegString("CourtSpokeParseA4");
                    Regex rp = new Regex(rpReg);
                    string chineseNumber = "一二三四五六七八九123456789";
                    var accused = ListName.Where(a => a.ES_SuitDrgreeID == suitid).OrderBy(a => a.ES_RoleIndex).ToList();
                    Match m = bei.Match(newOriginalText);
                    #region 进行提取
                    while (m != null && m.Value != string.Empty && accused.Count > 0)//
                    {
                        string r = rp.Replace(m.Value, "");
                        //只出现一次 比如 被一 被告一的替换
                        if (r.ToArray().Count() == 1)
                        {
                            char cnum = m.Value.ToArray().Last().ToString().ToCharArray().First();
                            int num = chineseNumber.ToArray().ToList().FindIndex(a => a == cnum);
                            if ((num % 9 + 1.0) <= accused.Count)
                            {
                                string s = newOriginalText.Substring(m.Index, m.Value.Length);
                                newOriginalText = newOriginalText.Remove(m.Index, m.Length); //删除匹配到的内容
                                if (string.IsNullOrEmpty(flag))
                                {
                                    var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                    if (accuse != null)
                                    {
                                        newOriginalText = newOriginalText.Insert(m.Index, "被告" + accuse.ES_FullName);
                                    }
                                }
                                else
                                {
                                    var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                    if (accuse != null)
                                    {
                                        newOriginalText = newOriginalText.Insert(m.Index, accuse.ES_FullName);
                                    }
                                }
                            }
                            else
                            {
                                if (accused.Count > 9)
                                {
                                    string s = newOriginalText.Substring(m.Index, m.Value.Length);
                                    newOriginalText = newOriginalText.Remove(m.Index, m.Length); //删除匹配到的内容
                                    if (string.IsNullOrEmpty(flag))
                                    {
                                        var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                        if (accuse != null)
                                        {
                                            newOriginalText = newOriginalText.Insert(m.Index, "被告" + accuse.ES_FullName);
                                        }
                                    }
                                    else
                                    {
                                        var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                        if (accuse != null)
                                        {
                                            newOriginalText = newOriginalText.Insert(m.Index, accuse.ES_FullName);
                                        }
                                    }
                                }
                            }
                        }
                        //出现多次 如 被一、二、三的替换
                        else
                        {
                            string replaceText = "";
                            string[] result = r.Split(new char[] { '、', ',', ',' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (var it in result)
                            {
                                try
                                {
                                    int num = (int)int.Parse(LdFormat.DecodeNumberCn(it.ToString()).ToString());
                                    num -= 1;
                                    if (num <= accused.Count)
                                    {
                                        if (string.IsNullOrEmpty(flag))
                                        {
                                            replaceText = replaceText + "被告" + accused[num].ES_FullName + "、";

                                        }
                                        else
                                        {
                                            replaceText = replaceText + accused[num].ES_FullName + "、";

                                        }
                                    }
                                }
                                catch (Exception err)
                                {
                                    replaceText = replaceText + it;

                                }
                            }
                            newOriginalText = newOriginalText.Remove(m.Index, m.Length);
                            //判断传进来的是被告三、还是被告三、四
                            if (result.Length == 1)
                            {
                                newOriginalText = newOriginalText.Insert(m.Index, replaceText);
                            }
                            else
                            {
                                newOriginalText = newOriginalText.Insert(m.Index, replaceText.Remove(replaceText.Length - 1, 1));
                            }
                        }

                        m = bei.Match(newOriginalText);
                    }
                    #endregion
                }
                catch (Exception err)
                {

                }
            }
            //IAnalysis analysis;
            //switch (caseType)
            //{
            //    case "b2":
            //        analysis = new B2AnalysisModel();
            //        break;
            //    case "b34":
            //        analysis = new B34AnalysisModel();
            //        break;
            //    default:
            //        analysis = new CommonAnalysisModel();
            //        break;
            //}
            CommonAnalysisModel analysis = new CommonAnalysisModel() { CaseType = caseType };
            if (analysis != null)
            {
                newOriginalText = analysis.Satrct(ListName, newOriginalText, flag);
            }
            if (caseType == "jb1")
            {
                string regstr = "(?<!犯罪嫌疑人|被告人|被告)(@{Name})".Replace("@{Name}", name);
                Regex bei = new Regex(regstr);
                Match m = bei.Match(newOriginalText);
                while (m != null && !string.IsNullOrEmpty(m.Value))
                {
                    newOriginalText = newOriginalText.Remove(m.Index, m.Length);
                    newOriginalText = newOriginalText.Insert(m.Index, "被告" + m.Value);
                    m = bei.Match(newOriginalText);
                }
                newOriginalText = newOriginalText.Replace("犯罪嫌疑人", "被告");
                newOriginalText = newOriginalText.Replace("被告", "被告人");
            }
            return newOriginalText.Replace("**1", "原告方").Replace("**2", "被告方").Replace("**3", "原、被告");
        }



        /// <summary>
        /// 返回匹配到的人员集合&*
        /// </summary>
        /// <param name="relatList">匹配人员集合</param>
        /// <param name="proxyRoleName">代理角色</param>
        /// <returns>匹配到的人员集合</returns>
        public IList<ElementSpokeName> GetMatchSpokeManByRoleName(IList<ElementSpokeName> relatList, string proxyRoleName, string casetype = "")
        {
            string suitid = "90";
            if (casetype == "jb1")
            {
                suitid = "297";
            }
            if (relatList.Any(a => a.ES_FullName == proxyRoleName))
            {
                return new List<ElementSpokeName>() { relatList.First(a => a.ES_FullName == proxyRoleName) };
            }
            #region 处理二被告 各被告这种格式
            ChnNumFormat chn = new ChnNumFormat();
            string cnReg = RuleParseClass.GetRegString("CourtSpokeParseA21");
            string cncount = Regex.Match(proxyRoleName, cnReg).Value;
            if (cncount == "两") cncount = "二";
            if (cncount == "各")
            {
                return relatList.Where(a => a.ES_SuitDrgreeID == suitid).ToList();
            }
            if (cncount == "二" || cncount == "三" || cncount == "四" || cncount == "五" || cncount == "六")
            {
                try
                {
                    string spnamesuit = RuleParseClass.GetParseValue("CourtSpokeParseA44", proxyRoleName);
                    if (chn.NumToChn(this.spokenamelist.Where(a => a.ES_SuitDegreeName == spnamesuit).Count().ToString()) == cncount)
                    {
                        string roleRegjuese = RuleParseClass.GetRegString("CourtSpokeParseA20");
                        Regex reg = new Regex(roleRegjuese);
                        return relatList.Where(a => a.ES_SuitDegreeName == spnamesuit).ToList();
                    }
                }
                catch (Exception)
                {


                }

                if (chn.NumToChn(this.spokenamelist.Where(a => a.ES_SuitDrgreeID == suitid).Count().ToString()) == cncount)
                {

                    string roleRegjuese = RuleParseClass.GetRegString("CourtSpokeParseA20");
                    Regex reg = new Regex(roleRegjuese);
                    return relatList.Where(a => a.ES_SuitDrgreeID == suitid).ToList();
                }
                else
                {
                    return new List<ElementSpokeName>();
                }
            }
            #endregion

            #region 多人员匹配方案
            List<ElementSpokeName> spokeList = new List<ElementSpokeName>();
            string roleReg = RuleParseClass.GetRegString("CourtSpokeParseA20");
            IList<double> roleIndexList = new List<double>();
            if (proxyRoleName.IndexOf("、") > 0 && !proxyRoleName.Contains("原"))
            {
                List<string> spokemans = MultiSpokeManParse.Parse(proxyRoleName);
                foreach (string spoker in spokemans)
                {
                    List<ElementSpokeName> returnlist = new List<ElementSpokeName>();
                    returnlist = GetSpokerManByOridinalAndRoleName(relatList, spoker);
                    if (returnlist.Count != 0)
                    {
                        if (spokeList.Contains(returnlist[0]))
                        {
                            if (returnlist.Count > 1)
                            {
                                spokeList.Add(returnlist[1]);
                            }
                        }
                        else
                        {
                            spokeList.Add(returnlist[0]);
                        }
                    }
                }
            }
            else
            {
                string roleNamejuese = Regex.Replace(proxyRoleName, roleReg, "");
                if (casetype == "jb1" && roleNamejuese == "被告")
                {
                    roleNamejuese = "犯罪嫌疑人";
                }
                List<char> roleindex = Regex.Match(proxyRoleName, roleReg).ToString().ToArray().ToList();
                if (proxyRoleName.StartsWith("第") && roleindex.Count > 1)
                {
                    foreach (char item in roleindex)
                    {
                        double roleindexNum = LdFormat.DecodeNumberCn(item.ToString());
                        if (roleindexNum != 0)
                        {
                            List<ElementSpokeName> spkerman = relatList.Where(a => a.ES_SuitDegreeName == roleNamejuese).ToList();
                            if (spkerman.Count > (roleindexNum - 1))
                            {
                                spokeList.Add(spkerman[Convert.ToInt32(roleindexNum - 1)]);
                            }
                        }
                    }
                }
                else
                {
                    spokeList = GetSpokerManByOridinalAndRoleName(relatList, proxyRoleName);
                }
            }
            if (spokeList.Count == 0)
            {
                if (proxyRoleName == "被代")
                {
                    spokeList = relatList.Where(a => a.ES_Role == "被1代").ToList();
                }
            }
            #endregion

            return spokeList;
        }

        /// <summary>
        /// 通过rolename找人  返回匹配的集合
        /// </summary>
        /// <param name="relatList"></param>
        /// <param name="proxyRoleName"></param>
        /// <returns></returns>
        public virtual List<ElementSpokeName> GetSpokerManByOridinalAndRoleName(IList<ElementSpokeName> relatList, string proxyRoleName)
        {
            List<ElementSpokeName> spokeList = new List<ElementSpokeName>();
            string ptReg = RuleParseClass.GetRegString("CourtSpokeParseA18");
            string roleReg = RuleParseClass.GetRegString("CourtSpokeParseA20");
            string roleName = Regex.Replace(proxyRoleName, roleReg, "");
            IList<ElementSpokeName> roleList = relatList.Where(a => a.ES_SuitDrgreeID.Contains(roleName)).ToList();
            if (roleList.Count > 0)
            {
                List<char> rolenum = Regex.Match(proxyRoleName, ptReg).ToString().ToArray().ToList();
                if (rolenum.Count > 0)
                {
                    double roleindexNum = 0;
                    for (int i = 0; i < rolenum.Count; i++)
                    {
                        roleindexNum += LdFormat.DecodeNumberCn(rolenum[i].ToString());
                    }
                    roleList = roleList.Where(a => a.ES_RoleIndex == roleindexNum.ToString() && a.ES_SuitDegreeName.Contains(roleName)).ToList();
                }
            }
            if (spokeList.Count == 0)
            {

                string role = Regex.Replace(proxyRoleName, roleReg, "");
                List<char> rolenum = Regex.Match(proxyRoleName, ptReg).ToString().ToArray().ToList();
                if (rolenum.Count > 0)
                {
                    double roleindexNum = 0;
                    for (int i = 0; i < rolenum.Count; i++)
                    {
                        roleindexNum += LdFormat.DecodeNumberCn(rolenum[i].ToString());
                    }
                    var spokerman = relatList.Where(a => a.ES_RoleIndex == roleindexNum.ToString() && a.ES_SuitDegreeName!=null && a.ES_SuitDegreeName.Contains(role)).FirstOrDefault<ElementSpokeName>();
                    if (spokerman != null)
                    {
                        spokeList.Add(spokerman);
                    }
                }
            }
            if (spokeList.Count == 0)
            {
                var mspoke = from spoke in relatList
                             where (spoke.ES_SuitDegreeName == proxyRoleName)
                             || (spoke.ES_ShortName == proxyRoleName)
                             || (spoke.ES_ShortName == proxyRoleName)
                             select spoke;
                spokeList = mspoke.ToList<ElementSpokeName>();
                if (proxyRoleName == "被告" && spokeList.Count != 1)
                {
                    //spokeList = new List<ElementSpokeName>();
                }
                if (proxyRoleName == "原告" && spokeList.Count != 1)
                {
                    //spokeList = new List<ElementSpokeName>();
                }

            }

            return spokeList;
        }
        /// <summary>
        /// 在人员名称替换前置处理
        /// </summary>
        /// <param name="originalText">需替换原文</param>
        public string dealPre(string originalText)
        {
            string fReg = RuleParseClass.GetRegString("CourtSpokeParseA7");
            Regex f = new Regex(fReg);
            originalText = f.Replace(originalText, "原告被告");//处理原被告无法识别的问题
            return originalText;
        }

        /// <summary>
        /// 原文格式化
        /// </summary>
        /// <param name="originalText">需替换原文</param>
        /// <returns></returns>
        public string FormatOriginalText(string originalText, IList<ElementSpokeName> ListName, string castype = "")
        {
            string suitid = "90";
            if (castype == "jb1")
            {
                suitid = "297";
            }
            List<ElementSpokeName> result = ListName.Where(a => a.ES_SuitDrgreeID == suitid).ToList();
            originalText = originalText.Replace("犯罪嫌疑人", "被告人");
            string newOriginalText = originalText;
            IList<string> existMatch = new List<string>();
            string fReg = RuleParseClass.GetRegString("CourtSpokeParseA2");
            Regex f = new Regex(fReg);

            if (ListName.Where(a => a.ES_SuitDrgreeID == suitid).ToList().Count == 1 && ListName.Where(a => a.ES_SuitDrgreeID == "89").ToList().Count == 1)
            {
                newOriginalText = f.Replace(originalText, "原告被告");
            }
            else
            {
                newOriginalText = f.Replace(originalText, "**3");
            }
            //处理 "被告一" 写为 "被告 一"的时候名称替换的问题
            Regex space = new Regex("\\s");
            newOriginalText = space.Replace(newOriginalText, "");
            string oMatchCollReg = "被告([一二三四五六七八九十]+)至(被告|原告)?([一二三四五六七八九十]+)";
            MatchCollection oMatchColl = Regex.Matches(newOriginalText, oMatchCollReg);
            foreach (Match oMatch in oMatchColl)
            {
                if (existMatch.Contains(oMatch.Value))
                    continue;
                else
                    existMatch.Add(oMatch.Value);
                IList<string> ChnNumbList = new List<string>();
                string startIndex = oMatch.Groups[1].Value;
                string endIndex = oMatch.Groups[2].Value;
                Regex reg = new Regex("[一二三四五六七八九十]+");
                if (!reg.IsMatch(endIndex))
                {
                    endIndex = oMatch.Groups[3].Value;
                }
                AmountConvert amountConvert = new AmountConvert();
                int startInt = Convert.ToInt32(LdFormat.DecodeNumberCn(startIndex));
                int endInt = Convert.ToInt32(LdFormat.DecodeNumberCn(endIndex));

                ChnNumFormat ChnNumFormatObj = new ChnNumFormat();
                List<string> rolelist = new List<string>();
                for (int i = startInt; i <= endInt; i++)
                {
                    string ChnNumbStr = ChnNumFormatObj.NumToChn(i.ToString());
                    var name = result.Where(a => int.Parse(a.ES_RoleIndex) == i).ToList();
                    string rolename = string.Empty;
                    foreach (var item in name)
                    {
                        rolename = "被告" + item.ES_FullName;
                    }
                    if (!string.IsNullOrWhiteSpace(rolename))
                    {
                        rolelist.Add(rolename);
                    }
                    ChnNumbList.Add(ChnNumbStr);
                }
                string replaceStr = string.Join<string>("、", rolelist);
                replaceStr = replaceStr.Substring(0, replaceStr.Length);
                newOriginalText = Regex.Replace(newOriginalText, oMatch.Value, replaceStr);
            }
            newOriginalText = newOriginalText.Replace("**3", "原告被告");
            return newOriginalText;
        }
    }
}
